package com.orangelife.mobile.main.fragment;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.curry.android.util.DialogHelper;
import com.curry.android.util.IntentHelper;
import com.curry.orangelife.mobile.R;
import com.markupartist.android.widget.PullToRefreshListView;
import com.orangelife.mobile.surrounding.activity.SearchConditionActivity;
import com.orangelife.mobile.common.fragment.OrangeLifeBaseFragment;
import com.orangelife.mobile.common.view.EmptyLayout;
import com.orangelife.mobile.constants.Constant;
import com.orangelife.mobile.main.adapter.HotGoodsListViewAdapter;
import com.orangelife.mobile.surrounding.biz.SurroundHttpBiz;
import com.orangelife.mobile.shoppingcart.activity.ShoppingCartActivity;
import com.orangelife.mobile.shoppingcart.biz.ShoppingCartBiz;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.ToastHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 周边
 *
 * @author chenxiang
 */
@Deprecated
public class Page3Fragment extends OrangeLifeBaseFragment {

    @Bind(R.id.llSearch)
    LinearLayout llSearch;
    @Bind(R.id.flShoppingCart)
    FrameLayout ibShoppcar;
    /** 购物车的数量 */
    @Bind(R.id.tvGoodNumber)
    TextView tvGoodNumber;
    @Bind(R.id.lvGoods)
    PullToRefreshListView lvGoods;
    @Bind(R.id.emptyLayout)
    EmptyLayout emptyLayout;
    private View homePageView;
    protected Dialog dialog;
    /** 一页中数据的条数，初始设置为8条 */
    private int pageSize = 8;
    /** 初始页，初始化为第一页 */
    private int pageNo = Constant.PAGE_NO_DEFAULT;
    /** 请求模式，上拉加载更多 */
    private final int REQ_MODE_LOAD_MORE = 0;
    private final int REQ_MODE_REFRESH = 1;
    private final int REQ_MODE_INIT = 2;
    private int currentReqMode = REQ_MODE_INIT;
    HotGoodsListViewAdapter<List<Map<String, Object>>> adapter;
    private List<List<Map<String, Object>>> refreshList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        currentReqMode = REQ_MODE_INIT;
        if (homePageView == null) {
            homePageView = inflater.inflate(R.layout.fragment_periphery_shop,
                    container, false);
            ButterKnife.bind(this, homePageView);
            findView();
        }
        /*缓存的view需要判断是否已经被加过parent，如果有parent需要从parent删除，要不然会发生这个view已经有parent的错误。*/
        ViewGroup parent = (ViewGroup) homePageView.getParent();
        if (parent != null) {
            parent.removeView(homePageView);
        }
        setShoppingCarNumber();
        requestGoodList();
        return homePageView;
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            dismissProgress();
            switch (msg.what) {
                case 1:
                    List list = SurroundHttpBiz.handleGoodList(msg.obj);
                    updateListView(list);
                    break;
                case 500:
                    if (isAdded()) {
                        ToastHelper.getInstance()._toast(
                                "网络不稳定");
                    }
                    break;
                case 1011:
                    isLogin(dialog);
                    break;
                default:
                    break;
            }
        }
    };

    private void findView() {
        setListViewAdapter();
        pullListView();
        llSearch.setOnClickListener(listener);
        ibShoppcar.setOnClickListener(listener);
        emptyLayout.setOnLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (refreshList != null && refreshList.size() > 0) {
                    refreshList.clear();//由于弹出框样式和是否有数据有关，为了避免弹出对话框，清空数据
                }
                currentReqMode = REQ_MODE_INIT;
                requestGoodList();
            }
        });
    }


    /***
     * listView设置adapter
     */
    private void setListViewAdapter() {
        refreshList = new ArrayList<>();
        adapter = new HotGoodsListViewAdapter<>(getActivity(), refreshList);
        lvGoods.setPullLoadEnable(false);
        lvGoods.setAdapter(adapter);
    }

    private View.OnClickListener listener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            switch (view.getId()) {
                case R.id.llSearch:
                    //跳转搜索界面
                    IntentHelper.getInstances().getIntent(getActivity(), SearchConditionActivity.class);
                    break;
                case R.id.flShoppingCart:
                    IntentHelper.getInstances().getIntent(getActivity(), ShoppingCartActivity.class);
                    break;
                default:
                    break;
            }

        }
    };


    @Override
    public void onResume() {
        super.onResume();
        BLog.getInstance().intAppmod(BLog.NEARBY);
    }

    /** 设置购物车商品数量 */
    private void setShoppingCarNumber() {
        int goodNum = ShoppingCartBiz.getGoodsCount();
        if (goodNum == 0) {
            tvGoodNumber.setVisibility(View.GONE);
        } else {
            tvGoodNumber.setVisibility(View.VISIBLE);
            tvGoodNumber.setText(goodNum + "");
        }
    }


    @Override
    public void onStop() {
        super.onStop();
        BLog.getInstance().outAppmod(BLog.NEARBY);
    }

    private void pullListView() {
        lvGoods.setXListViewListener(new PullToRefreshListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                pageNo = 1;
                currentReqMode = REQ_MODE_REFRESH;
                requestGoodList();
            }

            @Override
            public void onLoadMore() {
                currentReqMode = REQ_MODE_LOAD_MORE;
                requestGoodList();
            }
        });
    }

    private void showProgress() {
        if (currentReqMode == REQ_MODE_INIT) {
            if (refreshList != null && refreshList.size() > 0) {
                emptyLayout.setErrorType(EmptyLayout.HIDE_LAYOUT);
                dialog = DialogHelper.getInstance().createLoadingDialog(getActivity());
                dialog.show();
            } else {
                emptyLayout.setErrorType(EmptyLayout.NETWORK_LOADING);
            }
        }
    }

    private void dismissProgress() {
        if (currentReqMode == REQ_MODE_INIT) {
            if (refreshList != null && refreshList.size() > 0) {
                DialogHelper.closeDialog(dialog);
            } else {
                emptyLayout.dismiss();
            }
        }
    }

    private void requestGoodList() {
        if (isConnected(false)) {
            showProgress();
            SurroundHttpBiz.getGoodList(isConnected(false), pageNo, pageSize, null, handler, 1);
            if (currentReqMode == REQ_MODE_LOAD_MORE) {
                pageNo += 1;
            } else {
                pageNo = 1;
            }
        } else {
            emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR);
        }
    }

    /**
     * 刷新 拉下列表
     *
     * @param list
     */
    private void updateListView(List<List<Map<String, Object>>> list) {
        if (refreshList == null) {/*处理rl被置空的可能情况*/
            refreshList = new ArrayList<>();
        }
        if (currentReqMode == REQ_MODE_REFRESH) {
            lvGoods.stopRefresh();
            lvGoods.setRefreshTime(new Date().toLocaleString());
            refreshList.clear();
        } else if (currentReqMode == REQ_MODE_INIT) {
            refreshList.clear();
        } else {
            lvGoods.stopLoadMore();
        }
        if (list == null || list.size() == 0) {
            if (currentReqMode == REQ_MODE_REFRESH || currentReqMode == REQ_MODE_INIT) {
                emptyLayout.setErrorType(EmptyLayout.NODATA);
            }
            lvGoods.setPullLoadEnable(false);
        } else {
            lvGoods.setPullLoadEnable(true);
            refreshList.addAll(list);
        }
        adapter.setList(refreshList);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }
}
